﻿using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Common;
using Fast.Framework.CustomAttribute;
using System.Runtime.CompilerServices;

namespace Fast.Framework
{

    /// <summary>
    /// 动态代理
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class DynamicProxy<T> : DispatchProxy
    {
        /// <summary>
        /// 目标
        /// </summary>
        public T _target;

        /// <summary>
        /// 前
        /// </summary>
        private Action<MethodInfo, object[]> _before;

        /// <summary>
        /// 后
        /// </summary>
        private Action<MethodInfo, object[]> _after;

        /// <summary>
        /// 调用
        /// </summary>
        /// <param name="targetMethod">目标方法</param>
        /// <param name="args">参数</param>
        /// <returns></returns>
        protected override object Invoke(MethodInfo targetMethod, object[] args)
        {
            var flag = targetMethod.IsDefined(typeof(AopAttribute), true);
            object result = null;
            if (flag)
            {
                _before?.Invoke(targetMethod, args);
            }
            result = targetMethod.Invoke(_target, args);
            if (flag)
            {
                _after?.Invoke(targetMethod, args);
            }
            return result;
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="target">目标</param>
        /// <param name="before">前</param>
        /// <param name="after">后</param>
        /// <returns></returns>
        public T Create(T target, Action<MethodInfo, object[]> before = null, Action<MethodInfo, object[]> after = null)
        {
            object obj = Create<T, DynamicProxy<T>>();
            var proxy = obj as DynamicProxy<T>;
            proxy._target = target;
            proxy._before = before;
            proxy._after = after;
            obj = proxy;
            return (T)obj;
        }
    }
}
